<template>
  <div>
    <el-card shadow="never" class="margin-30">
      <el-checkbox v-model="expandAll" @change="handleExpandAll">展开/关闭</el-checkbox>
      <el-checkbox v-model="checkedAll" @change="handleCheckedAll">全选/取消全选</el-checkbox>
      <el-checkbox v-model="checkedAll" @change="handleCheckedAll2">全选/取消全选2</el-checkbox>
      <el-tree ref="tree" :data="menuList" :props="props" show-checkbox check-strictly node-key="id" />
      <el-button type="primary" size="mini" @click="doSave">确定</el-button>

    </el-card>

  </div>
</template>
<script>
import {
  findAllPermissions as findAllPermissionsApi
} from '@/api/auth/roles.js'
export default {
  name: 'Roles',
  mixins: [],
  data() {
    return {
      menuList: [],
      props: {
        label: 'title'
      },
      expandAll: false,
      checkedAll: false,
      permissionIds: [],
      allIds: []
    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.getPermissionList()
  },
  mounted() {
  },
  methods: {
    async getPermissionList() {
      const res = await findAllPermissionsApi()
      this.menuList = res.data.menus
    },
    handleExpandAll(val) {
      console.log('ExpandAll val==>', val)
      console.log('tree=>', this.$refs.tree)
      const nodesMap = this.$refs.tree.store.nodesMap
      for (const key in nodesMap) {
        const item = nodesMap[key]
        // if (val) {
        //   item.expanded = true
        // } else {
        //   item.expanded = false
        // }
        item.expanded = val
      }
    },
    handleCheckedAll(val) {
      const nodesMap = this.$refs.tree.store.nodesMap
      for (const key in nodesMap) {
        const item = nodesMap[key]
        item.checked = val
      }
    },
    handleCheckedAll2(val) {
      if (val) {
        this.getAllId(this.menuList)
        this.$refs.tree.setCheckedKeys(this.allIds)
      } else {
        this.allIds = []
        this.$refs.tree.setCheckedKeys(this.allIds)
      }
    },
    // 递归
    getAllId(arr) {
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        this.allIds.push(item.id)
        if (item.children && item.children.length > 0) {
          this.getAllId(item.children)
        }
      }
    },
    doSave() {
      this.permissionIds = this.$refs.tree.getCheckedKeys()
      console.log('this.permissionIds==>', this.permissionIds)
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
